﻿using System;
using System.Data;
using GeoWeb.DataContext;
using GeoWeb.Demo.DataContext;
using System.Xml;
using GeoWeb.Common;

namespace GeoWeb.Demo.CodeValue
{
    public partial class BPO_codeValues : System.Web.UI.Page
    {
        DbUtity db = new DbUtity();
        string OID = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            string flag = Request.Params["flag"];
            if (flag != null)
            {
                int pageIndex = 0;
                int pageSize = 0;
                string field = Request.Params["field"];
                string val = Request.Params["val"];
                string CodeClassifyOID = Request.Params["CodeClassifyOID"];
                string sortName = Request.Params["sortName"];
                string sortOrder = Request.Params["sortOrder"];
                string sorter = "";

                if (!string.IsNullOrEmpty(sortName) && !string.IsNullOrEmpty(sortOrder))
                {
                    sorter = string.Format(" order by {0} {1}", sortName, sortOrder);
                }
                pageIndex = Convert.ToInt32(Request.Params["pageIndex"]);
                pageSize = Convert.ToInt32(Request.Params["pageSize"]);
                switch (flag)
                {
                    case "flag_left":
                        string CodeTable = Request.Params["CodeTable"];
                        string condition = "";

                        if (!string.IsNullOrEmpty(CodeTable))
                        {
                            condition = " and (CodeTableID like '%" + CodeTable + "%' or CodeTableName like '%" + CodeTable + "%')";
                        }
                        Response.Write(GetParael(pageIndex, pageSize, sorter, condition));
                        break;
                    case "Left_2":
                        Response.Write(UpdateDate(field, val, CodeClassifyOID) ? "1" : "0");
                        break;
                    case "left_3":

                        Response.Write(DeleteDate(CodeClassifyOID));
                        Response.Flush();
                        break;
                    case "left_4":
                        //string txt_sign = Request.Params["txt_sign"];
                        //string txt_ChinaName = Request.Params["txt_ChinaName"];
                        string txt_sign = Request.Params["txt_sign"].ToString();
                        string txt_ChinaName = Request.Params["txt_ChinaName"].ToString();
                        Response.Write(InsertCodeClass(txt_sign, txt_ChinaName));
                        break;
                    case "Top_1":
                        string CodeTableID = Request.Params["CodeTableID"].ToString();
                        string codeName = Request.Params["CodeTableName"].ToString();
                        Response.Write(GetTrees(CodeTableID, codeName));

                        break;
                    case "bottom_1":
                        string CodeValueOIDs = Request.Params["CodeValueOID"].ToString();
                        string CodeNames = Request.Params["CodeName"].ToString();
                        Response.Write(CallBackCodeTable(CodeValueOIDs, CodeNames));
                        Response.Flush();
                        break;
                    case "bottom_2":
                        string type = Request.Params["type"].ToString();
                        string txtCodeID = Request.Params["CodeID"].ToString();
                        string txtCodeName = Request.Params["CodeName"].ToString();
                        string txtCodeTableID = Request.Params["CodeTableID"].ToString();
                        string txtCodeClassifyOID = Request.Params["CodeClassifyOID"].ToString();
                        string txtCodeValueID = Request.Params["CodeValueID"].ToString();
                        string msg = "";
                        try
                        {
                            switch (type)
                            {
                                case "root":
                                    Response.Write(GetInsertPanel(type, txtCodeID, txtCodeName, txtCodeTableID, txtCodeClassifyOID));
                                    break;
                                case "child":
                                    Response.Write(GetInsertChild(type, txtCodeID, txtCodeName, txtCodeTableID, txtCodeClassifyOID, txtCodeValueID));
                                    break;
                                case "delete":
                                    //  Response.Write(GetDelete(type,txtCodeValueID, txtCodeName, txtCodeClassifyOID));
                                    break;
                                case "update":
                                    Response.Write(UpdateTree(type, txtCodeClassifyOID, txtCodeValueID, txtCodeID, txtCodeName, txtCodeTableID));
                                    break;
                                default: break;
                            }
                        }
                        catch
                        {

                        }
                        break;
                    case "Expre":
                        string TableID = Request.Params["CodeTableID"];
                        string ClassifyOID = Request.Params["CodeClassifyOID"];
                        string ValueID = Request.Params["CodeValueID"];
                        Response.Write(GetDelete(ValueID, TableID, ClassifyOID));
                        break;
                    case "ExpreParent":
                        string CoidID = Request.Params["CodeTableID"];
                        string ClasssifgOID = Request.Params["CodeClassifyOID"];
                        string ValueOID = Request.Params["CodeValueID"];
                        Response.Write(DeleteSingParentID(CoidID, ClasssifgOID, ValueOID));
                        break;
                    default: break;
                }
                Response.End();
            }
        }

        /// <summary>
        /// 删除子节点
        /// </summary>
        /// <param name="CodeTableID"></param>
        /// <param name="CodeClassifyOID"></param>
        /// <param name="CodeValueID"></param>
        /// <returns></returns>
        private string DeleteSingParentID(string CodeTableID, string CodeClassifyOID, string CodeValueID)
        {
            try
            {
                db.Db.Delete<CodeValue>(new WhereClip(
                    "CodeValueOID=@CodeValueOID and CodeTableID=@CodeTableID and CodeClassifyOID=@CodeClassifyOID",
                    new SQLParameter[]{
                        new SQLParameter("@CodeValueOID", CodeValueID),
                        new SQLParameter("@CodeTableID", CodeTableID),
                        new SQLParameter("@CodeClassifyOID", CodeClassifyOID)
                    }
                ));
                return "1";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 添加节点
        /// </summary>
        /// <param name="type"></param>
        /// <param name="CodeID"></param>
        /// <param name="CodeName"></param>
        /// <param name="CodeTableID"></param>
        /// <param name="CodeClassifyOID"></param>
        /// <returns></returns>
        private string GetInsertPanel(string type, string CodeID, string CodeName, string CodeTableID, string CodeClassifyOID)
        {
            try
            {
                OID = Guid.NewGuid().ToString();
                db.Db.Insert<CodeValue>(
                    new Field[] {
                        new Field("CodeValueOID"),
                        new Field("CodeID"),
                        new Field("CodeName"),
                        new Field("CodeTableID"),
                        new Field("ParentOID"),
                        new Field("CodeClassifyOID")
                    },
                    new object[] {
                        OID,
                        CodeID,
                        CodeName,
                        CodeTableID,
                        "00000000-0000-0000-0000-000000000000",
                        CodeClassifyOID
                    }
                );
                return type + "|" + OID;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="type"></param>
        /// <param name="CodeID"></param>
        /// <param name="CodeName"></param>
        /// <param name="CodeTableID"></param>
        /// <param name="CodeClassifyOID"></param>
        /// <param name="CodeValueId"></param>
        /// <returns></returns>
        private string GetInsertChild(string type, string CodeID, string CodeName, string CodeTableID, string CodeClassifyOID, string CodeValueId)
        {

            try
            {
                OID = Guid.NewGuid().ToString();
                db.Db.Insert<CodeValue>(
                    new Field[] {
                        new Field("CodeValueOID"),
                        new Field("CodeID"),
                        new Field("CodeName"),
                        new Field("CodeTableID"),
                        new Field("ParentOID"),
                        new Field("CodeClassifyOID")
                    },
                    new object[] {
                        OID,
                        CodeID,
                        CodeName,
                        CodeTableID,
                        CodeValueId,
                        CodeClassifyOID
                    }
                );
                return type + "|" + OID;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 删除树结构数据
        /// </summary>
        /// <param name="type"></param>
        /// <param name="txtCodeValueID"></param>
        /// <param name="CodeName"></param>
        /// <param name="CodeClassifyOID"></param>
        /// <returns></returns>
        private string GetDelete(string txtCodeValueID, string CodeTableID, string CodeClassifyOID)
        {
            try
            {
                db.Db.Delete<CodeValue>(new WhereClip(
                    "(CodeValueOID=@CodeValueOID or ParentOID=@CodeValueOID) and CodeClassifyOID=@CodeClassifyOID and CodeTableID=@CodeTableID",
                    new SQLParameter[]{
                        new SQLParameter("@CodeValueOID", txtCodeValueID),
                        new SQLParameter("@CodeClassifyOID", CodeClassifyOID),
                        new SQLParameter("@CodeTableID", CodeTableID)
                    }
                ));
                return "1";
            }
            catch
            {
                return "";
            }
        }


        /// <summary>
        /// 更新树结构数据
        /// </summary>
        /// <param name="type"></param>
        /// <param name="CodeClassifyOID"></param>
        /// <param name="txtCodeValueID"></param>
        /// <param name="CodeID"></param>
        /// <param name="CodeName"></param>
        /// <param name="CodeTableId"></param>
        /// <returns></returns>
        private string UpdateTree(string type, string CodeClassifyOID, string txtCodeValueID, string CodeID, string CodeName, string CodeTableId)
        {
            try
            {
                db.Db.Update<CodeValue>(new Field[]{
                        new Field("CodeID"),
                        new Field("CodeName"),
                        new Field("CodeTableID")
                    }, new object[]{
                        CodeID,
                        CodeName,
                        CodeTableId
                    }, new WhereClip(
                        "CodeValueOID=@CodeValueOID and CodeClassifyOID=@CodeClassifyOID",
                        new SQLParameter[]{
                            new SQLParameter("@CodeValueOID", txtCodeValueID),
                            new SQLParameter("@CodeClassifyOID", CodeClassifyOID)
                        }
                    )
                );

                db.Db.Update<CodeClassify>(new Field("CodeTableID"),
                    CodeTableId, new WhereClip("CodeClassifyOID=@CodeClassifyOID", new SQLParameter("@CodeClassifyOID", CodeClassifyOID)));

                return type + "|";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取代码分类数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sorter"></param>
        /// <returns></returns>
        private string GetParael(int pageIndex, int pageSize, string sorter, string condition)
        {
            SqlSection sqls = db.Db.FromSql(string.Format(@"select 1 from CodeClassify where 1=1 {0}", condition), null);
            int count = sqls.ToTable().RowCount;

            sqls = db.Db.FromSql(string.Format(@"select top {0} * from CodeClassify where CodeClassifyOID not in (select top {1} CodeClassifyOID from CodeClassify where 1=1 {2} {3}){4} {5}", pageSize, pageSize * (pageIndex - 1), condition, sorter, condition, sorter), null);
            DataTable tb = sqls.ToTable() as DataTable;

            try
            {
                JsonHelper jsonh = new JsonHelper();
                return "{\"DataTable\":" + jsonh.DataTableToJSON(tb) + ",\"RowCount\":" + count + "}";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <returns></returns>
        private bool UpdateDate(string field, string val, string CodeClassifyOID)
        {
            try
            {
                db.Db.Update<CodeClassify>(new Field(field), val, new WhereClip("CodeClassifyOID=@CodeClassifyOID", new SQLParameter("@CodeClassifyOID", CodeClassifyOID)));
                if (field != "CodeTableName")
                {
                    db.Db.Update<CodeValue>(new Field(field), val, new WhereClip("CodeClassifyOID=@CodeClassifyOID", new SQLParameter("@CodeClassifyOID", CodeClassifyOID)));
                }
                return true;
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="CodeClassifyOID"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        private string DeleteDate(string CodeClassifyOID)
        {
            try
            {
                db.Db.Delete<CodeClassify>(new WhereClip("CodeClassifyOID=@CodeClassifyOID", new SQLParameter("@CodeClassifyOID", CodeClassifyOID)));
                db.Db.Delete<CodeValue>(new WhereClip("CodeClassifyOID=@CodeClassifyOID", new SQLParameter("@CodeClassifyOID", CodeClassifyOID)));
                return "1";
            }
            catch
            {
                return "0";
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="CodeTableID"></param>
        /// <param name="CodeTableName"></param>
        /// <returns></returns>
        private string InsertCodeClass(string CodeTableID, string CodeTableName)
        {
            try
            {
                db.Db.Insert<CodeClassify>(new Field[]{
                    new Field("CodeClassifyOID"),
                    new Field("CodeTableID"),
                    new Field("CodeTableName")
                }, new object[]{
                    Guid.NewGuid(),
                    CodeTableID,
                    CodeTableName
                });
                return "1";
            }
            catch
            {
                return "";
            }
        }

        private string GetTrees(string CodeTableID, string CodeTableName)
        {
            XmlDocument XMLdoc = new XmlDocument();
            XmlDeclaration head = XMLdoc.CreateXmlDeclaration("1.0", "UFT-8", "");
            XmlElement treeNode = XMLdoc.CreateElement("tree");
            XMLdoc.AppendChild(treeNode);
            AddAttribute(XMLdoc, "id", "0", treeNode);
            GetTrew(XMLdoc, GetDataTable(CodeTableID, CodeTableName), "00000000-0000-0000-0000-000000000000", treeNode);
            string xml = XMLdoc.OuterXml;
            return xml;
        }

        private DataTable GetDataTable(string CodeTableID, string CodeTableName)
        {
            string strsql = " select * from CodeClassify A,codeValue B where A.CodeClassifyOID=b.CodeClassifyOID";
            if (!string.IsNullOrEmpty(CodeTableID) && !string.IsNullOrEmpty(CodeTableName))
            {
                strsql += " and a.CodeTableID='" + CodeTableID + "' and  A.CodeTableName='" + CodeTableName + "'";
            }
            strsql += " order by B.CodeID,B.CodeName";
            SqlSection sqls = db.Db.FromSql(strsql, null);
            return sqls.ToTable() as DataTable;
        }

        private XmlElement GetTrew(XmlDocument XMLdoc, DataTable det, string ParentOID, XmlElement ParentNode)
        {
            for (int i = 0; i < det.Rows.Count; i++)
            {
                string oid = det.Rows[i]["CodeValueOID"].ToString().ToLower();
                string pid = det.Rows[i]["ParentOID"].ToString().ToLower();
                if (ParentOID.ToLower() == pid)
                {
                    XmlElement item = XMLdoc.CreateElement("item");
                    AddAttribute(XMLdoc, "text", det.Rows[i]["codeName"].ToString(), item);
                    AddAttribute(XMLdoc, "id", det.Rows[i]["CodeValueOID"].ToString(), item);
                    AddAttribute(XMLdoc, "CodeID", det.Rows[i]["CodeID"].ToString(), item);
                    AddAttribute(XMLdoc, "ParentOID", det.Rows[i]["ParentOID"].ToString(), item);
                    XmlNode items = (XmlNode)item;
                    ParentNode.AppendChild(items);
                    GetTrew(XMLdoc, det, oid, item);
                }
            }

            return ParentNode;
        }

        private DataTable FilterByparentOID(DataTable det, string parentOID)
        {
            DataView dv = det.DefaultView;
            dv.RowFilter = " B.parentOID='" + parentOID + "'";
            return dv.ToTable();
        }

        private void AddAttribute(XmlDocument xmldoc, string name, string value, XmlNode node)
        {
            XmlAttribute attribute = xmldoc.CreateAttribute(name);
            attribute.Value = value;
            node.Attributes.Append(attribute);
        }

        private string CallBackCodeTable(string CodeValueOID, string CodeName)
        {
            string CodeID = "";

            string Table = "CodeClassify A,codeValue B";
            string sql = "select A.CodeTableID,CodeID,CodeName from " + Table + "  where A.CodeClassifyOID=b.CodeClassifyOID ";
            if (!string.IsNullOrEmpty(CodeValueOID) && !string.IsNullOrEmpty(CodeName))
            {
                sql += "  and B.CodeValueOID='" + CodeValueOID + "' and  B.CodeName='" + CodeName + "'";
            }
            SqlSection sqls = db.Db.FromSql(sql, null);
            DataTable dtTable = sqls.ToTable() as DataTable;
            if (dtTable.Rows.Count > 0)
            {
                CodeID = dtTable.Rows[0]["CodeID"].ToString();
            }
            else
            {
                CodeID = "";
            }

            return CodeID;
        }
    }
}